<?php
/**
 * Created by PhpStorm.
 * User: thanatos
 * Date: 2017/11/11
 * Time: 上午10:48
 */

namespace common\models;

use Yii;
use common\components\OauthUserProvider;
use yii\base\Model;
use yii\db\Exception;

/**
 * 统一登录验证类
 *
 * @property OauthUserProvider $oauth 第三方用户信息
 *
 * @package common\models
 */
class LoginForm extends Model
{
    public $oauth;
    
    private $_user;
    
    /** 默认用户名密码验证 */
    const SCENARIO_DEFAULT = 'default';
    /** 第三方登录验证 */
    const SCENARIO_OAUTH   = 'oauth';
    
    /** 保存登录时间 */
    const LOGIN_TIME = 15*3600*24;
    
    public function scenarios()
    {
        return [
            self::SCENARIO_OAUTH => ['oauth'],
        ];
    }
    
    public function rules()
    {
        return [
            ['oauth', 'validataOauth', 'on' => self::SCENARIO_OAUTH],
        ];
    }
    
    public function login($params)
    {
        $this->attributes = $params;
        if( $this->validate() ){
            // 第三方登录需要验证是否自动注册
            if( $this->scenario == self::SCENARIO_OAUTH ){
                /*if( $this->getUser()->primaryKey === null ){
                    // 如果用户为空自动注册
                    $this->register();
                }*/
                // 登录操作
                $this->doLogin();
            }
        }else{
            return false;
        }
    }
    
    protected function register()
    {
        $model = $this->getUser();
        // 随机密码
        $model->salt = Yii::$app->security->generateRandomString(4);
        $model->password = $this->encryptPassSalt($model->salt, $model->salt);
        $model->isPassword = 0;
        
        // TODO 待添加其他逻辑
        $model->coopId = 0;
        $model->source = 'tbzpc';
        $model->created = date('Y-m-d H:i:s');
        $model->save();
        // 后续处理用户名
        $model->name = 'u'.$model->primaryKey;
        $model->save();
        
        if( $model->hasErrors() ){
            throw new \yii\base\Exception(json_encode($this->getErrors()));
        }
        
    }
    
    protected function doLogin()
    {
        $this->getUser()->primaryKey and Yii::$app->user->login($this->getUser(), static::LOGIN_TIME);
    }
    
    
    /**
     * @return User|null
     */
    protected function getUser()
    {
        if( $this->_user === null ){
            if( $this->scenario === self::SCENARIO_OAUTH ){
                $this->_user = $this->oauth->getMember();
            }
        }
        return $this->_user;
    }
    
    /**
     * 验证微信用户信息
     * @param $attribute
     * @param $params
     * @return bool
     */
    public function validataOauth($attribute, $params)
    {
        /** @var WechatUser $model */
        $model = $this->$attribute;
        if( !($model instanceof OauthUserProvider) ){
            $this->addError($attribute, 'wechatUser is must instanceof' . OauthUserProvider::className());
            return false;
        }
        if( !$model->validate() ){
            $this->addError($attribute, 'wechatUser 数据格式不正确');
            return false;
        }
    }

    
    private function encryptPassSalt($pass, $salt){
        return (empty($pass) || empty($salt)) ? null : md5(md5($pass) . $salt);
    }
}